package com.gulimall.search.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.utils.R;
import com.guli.common.vo.SkuEsModel;
import com.gulimall.search.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 武者
 * @title: SearchServiceImpl
 * @projectName gulimall-zhuan5
 * @description:
 * @date 2022/1/7 17:04
 */
@Service
public class SearchServiceImpl {

    @Autowired
    RestHighLevelClient client;



    public R addAll(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest request = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {


            IndexRequest re = new IndexRequest("product");
            re.id(skuEsModel.getSkuId()+"");
            String jsonString = JSON.toJSONString(skuEsModel);
            re.source(jsonString, XContentType.JSON);
            request.add(re);
        }
        BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);

        if (bulkResponse.hasFailures()) {
            return R.error();
        }



        return R.ok();
    }

    public SearchResult search(SearchParam searchParam) throws IOException {

        SearchRequest searchRequest = new SearchRequest("product");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (StringUtils.isNotBlank(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }

        boolQueryBuilder.must(QueryBuilders.termQuery("hasStock",searchParam.isHasStock()));

        if (StringUtils.isNotBlank(searchParam.getSkuPrice())&& searchParam.getSkuPrice().contains("_")){
            String skuPrice = searchParam.getSkuPrice();

            String[] split = skuPrice.split("_");
            if (skuPrice.startsWith("_")){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").lte(split[1]));
            }else if (skuPrice.endsWith("_")){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").gte(split[0]));
            }else {
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").lte(split[1]).gte(split[0]));
            }
        }
        //品牌查询
        if (searchParam.getBrandId()!=null && searchParam.getBrandId().size()>0){

            boolQueryBuilder.must(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }

        //分类查询
        if (searchParam.getCatalog3Id()!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }

        // 属性查找
        if (searchParam.getAttrs()!=null && searchParam.getAttrs().size()>0){
            for (String attr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();

                String[] s = attr.split("_");

                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrId",s[0]));

                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",s[1].split(":")));

                boolQueryBuilder.must(QueryBuilders.nestedQuery("attrs",nestedBoolQueryBuilder, ScoreMode.None));

            }
        }

        //************  聚合  ******************************
        //品牌聚合

        //2.1 brandIdAgg 品牌聚合
        TermsAggregationBuilder brandAggregation = AggregationBuilders.terms("brandIdAgg").field("brandId");

        brandAggregation.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName"));
        brandAggregation.subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg"));
        searchSourceBuilder.aggregation(brandAggregation);
        //2.2 cateIdAgg 分类聚合
        TermsAggregationBuilder cateIdAgg = AggregationBuilders.terms("cateIdAgg").field("catalogId");
        cateIdAgg.subAggregation(AggregationBuilders.terms("cateNameAgg").field("catalogName"));
        searchSourceBuilder.aggregation(cateIdAgg);

        //2.3 属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attrAgg", "attrs");
        //构建attrId属性子聚合
        TermsAggregationBuilder attrIdAggregation = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        //attrName聚合
        attrIdAggregation.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"));
        //attrValue聚合
        attrIdAggregation.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"));

        nested.subAggregation(attrIdAggregation);
        searchSourceBuilder.aggregation(nested);




        //分页
        searchSourceBuilder.from((searchParam.getPageNum()-1)*searchParam.getSize());
        searchSourceBuilder.size(searchParam.getSize());

        //高亮
        searchSourceBuilder.highlighter(new HighlightBuilder().field("skuTitle").preTags("<span style='color:red'>").postTags("<span>"));

        searchSourceBuilder.query(boolQueryBuilder);

        searchRequest.source(searchSourceBuilder);

        //执行
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //三.处理结果
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        SearchHit[] searchHits = hits.getHits();
        //所有商品信息
        List<SkuEsModel> products = new ArrayList<>();

        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, new TypeReference<SkuEsModel>() {
            });
            skuEsModel.setSkuId(Long.parseLong(id));//赋值主键
            //处理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("skuTitle");
            if(highlight != null){
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                skuEsModel.setSkuTitle(fragmentString);
            }

            products.add(skuEsModel);
        }


        //3 ================处理聚合=================
        Aggregations aggregations = searchResponse.getAggregations();
        //3.1 brandIdAgg 品牌聚合
        List<BrandVo> brandVos = new ArrayList<>();
        //！！！ 构建聚合时是什么类型 就用什么类型接受
        Terms brandIdAgg = aggregations.get("brandIdAgg");
        for (Terms.Bucket bucket : brandIdAgg.getBuckets()) {
            BrandVo brandVo = new BrandVo();
            //品牌id
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            //获取brandIdAgg聚合的子聚合
            Aggregations bucketAggregations = bucket.getAggregations();
            //品牌名称 //！！！ 构建聚合时是什么类型 就用什么类型接受
            Terms brandNameAgg = bucketAggregations.get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //品牌图片
            Terms brandImgAgg = bucketAggregations.get("brandImgAgg");
            brandVo.setBrandImg(brandImgAgg.getBuckets().get(0).getKeyAsString());
            brandVos.add(brandVo);
        }

        //3.2 cateIdAgg 分类聚合
        ArrayList<CatalogVo> catalogVos = new ArrayList<>();
        //！！！ 构建聚合时是什么类型 就用什么类型接受
        Terms cateIdAggregations = aggregations.get("cateIdAgg");
        for (Terms.Bucket bucket : cateIdAggregations.getBuckets()) {
            CatalogVo catalogVo = new CatalogVo();
            //分类id
            catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
            //获取桶的子绝活
            Aggregations bucketAggregations = bucket.getAggregations();
            //分类名称 //！！！ 构建聚合时是什么类型 就用什么类型接受
            Terms cateNameAgg = bucketAggregations.get("cateNameAgg");
            String cateName = cateNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(cateName);
            catalogVos.add(catalogVo);
        }



        //3.3 属性nested聚合处理
        ArrayList<AttrVo> attrVos = new ArrayList<>();

        Nested attrAgg = aggregations.get("attrAgg");
        Aggregations nestedSubAggregations = attrAgg.getAggregations();
        //attrId聚合
        Terms attrIdAgg = nestedSubAggregations.get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            AttrVo attrVo = new AttrVo();
            //属性id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            //获取子聚合
            Aggregations bucketAggregations = bucket.getAggregations();
            //属性名
            Terms attrNameAgg = bucketAggregations.get("attrNameAgg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            //属性值
            Terms attrValueAgg = bucketAggregations.get("attrValueAgg");
            ArrayList<String> atvs = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                //收集所有value
                atvs.add(attrValueAggBucket.getKeyAsString());
            }
            attrVo.setAttrValue(atvs);
            attrVos.add(attrVo);
        }



        SearchResult searchResult = new SearchResult();
        searchResult.setProducts(products);
        searchResult.setBrands(brandVos);
        searchResult.setCatalogs(catalogVos);
        searchResult.setAttrs(attrVos);
        searchResult.setTotal(numHits);//总数
        //总页数
        int size = searchParam.getSize();
        int totalPage = (int) (numHits%size==0?numHits/size:(numHits/size+1));
        searchResult.setTotalPage(totalPage);
        //页数导航页
        ArrayList<Integer> paNav = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            paNav.add(i);
        }
        searchResult.setPaNav(paNav);
        //当前页
        searchResult.setPageNum(searchParam.getPageNum());
        return searchResult;
    }
}
